package com.gupao.vip.netty;

import cn.hutool.core.convert.Convert;
import com.gupao.vip.bio.Constants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.util.Objects;

public class TimeClient {

    public void connect(int port, String host) throws Exception{
        //配置客户端NIO线程组
        //客户端处理I/O读写的NioEventLoopGroup线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();

            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        }finally{
            //优雅退出，释放NIO线程组
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = Constants.DEFAULT_PORT;
        if(Objects.nonNull(args) &&  args.length > 0){
            port = Convert.toInt(args[0], Constants.DEFAULT_PORT);
        }
        try {
            new TimeClient().connect(port, Constants.DEFAULT_IP);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
